package org.robert.export_client.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author robert
 * @Date 2024/1/13 20:15
 **/
@Slf4j
public class ExcelDictAdapter<T> {


    public void setDict(List<T> list, Map<String, Map<String, String>> dictMap){
        if(CollectionUtils.isEmpty(list) || MapUtils.isEmpty(dictMap)){
            return;
        }
        for (T t : list) {
            // 获取类的所有属性
            Field[] fields = t.getClass().getDeclaredFields();
            // 检查每个属性是否包含特定的注解
            for (Field field : fields) {
                if (field.isAnnotationPresent(ExportDict.class)) {
                    field.setAccessible(true);
                    ExportDict exportDict = field.getAnnotation(ExportDict.class);
                    // 获取注解的值
                    String value = exportDict.value();
                    boolean isSplit = exportDict.isSpilt();
                    // 获取属性的值
                    try{
                        String attributeValue = (String) field.get(t);
                        if(StringUtils.isNotBlank(value) || StringUtils.isNotBlank(attributeValue)){
                            Map<String, String> dict = dictMap.get(value);
                            // 是否需要分割
                            if(isSplit){
                                String split = exportDict.spilt();
                                String connect = exportDict.connect();
                                if(StringUtils.isNotBlank(split) || StringUtils.isNotBlank(connect)){
                                    String[] strings = attributeValue.split(split);
                                    StringBuilder builder = new StringBuilder();
                                    for (String string : strings) {
                                        String s = dict.get(string);
                                        if(StringUtils.isNotBlank(s)){
                                           builder.append(s).append(connect);
                                        }
                                    }
                                    field.set(t, builder.toString());
                                }
                            }else{
                                field.set(t, dict.get(attributeValue));
                            }
                        }
                    }catch (Exception e){
                        log.error("字段字典转换异常，filed={}", field.getName());
                        log.error(e.getMessage(), e);
                    }
                }
            }
            // log.info("转换后的对象：{}", JSONObject.toJSONString(t));
        }
    }


}
